import { useEffect, useRef, useState } from "react";
import st from "./user.module.css";
import { useNavigate } from "react-router";
// userItem组件
const UserItem = ({ item, onSelect, select, isBirth = false }: any) => {
  // 图片dom
  const imgRef = useRef<any>(null);
  // 控制图片是否加载
  const [imgVisable, setImgVisable] = useState(false);
  // 路由跳转
  const navigate = useNavigate();
  // 头像图片采用intersection处理的懒加载效果
  useEffect(() => {
    const interOb = new IntersectionObserver(
      (entries) => {
        if (entries[0].intersectionRatio <= 0) {
        } else {
          setImgVisable(true);
        }
      },
      {
        threshold: 1, //配置项，0-1完全进入视窗才会触发上述回调函数
      }
    );
    interOb.observe(imgRef.current);
  }, []);

  return (
    <div
      className={st.userItem}
      onClick={!isBirth ? () => navigate(`/vipdetail/${item.id}`) : () => {}}
    >
      {isBirth && (
        <div
          className={`${st.checkBox} ${
            select.find((it: string) => it === item.id) ? st.select : ""
          }`}
          onClick={() => onSelect(item.id)}
        ></div>
      )}
      <img
        className={st.avatar}
        src={imgVisable ? item.url : null}
        ref={imgRef}
      />
      <div className={st.textArea}>
        <div className={st.top}>
          <span className={st.nickname}>{item.nickname}</span>
          {isBirth && <span className={st.signal}>今</span>}
        </div>
        <div className={st.phone}>{item.phone}</div>
      </div>
    </div>
  );
};
export default UserItem;
